local PlayerService = require "modules.player.PlayerService"
local GamesConfig = require "modules.games.GamesConfig"
local RoomConst = require "modules.room.RoomConst"
local RoomService = require "modules.room.RoomService"
local Service = require "core.Service"
local games = GamesConfig.games

local M = {}

function M.CS_ROOM_CREATE(player, data)
    local gameName = data.gameName
    if not games[gameName] then
        return {
            code = RoomConst.CREATE_RESULT_CODE.GAME_NOT_OPEN
        }
    end

    if player.room then
        return {
            code = RoomConst.CREATE_RESULT_CODE.ALREADY_IN_ROOM
        }
    end

    local code, room = RoomService:createRoom(player.id, data)
    local result = {
        code = code
    }

    if not room then
        return result
    end

    player.room = Service:new(room)
    return result
end

function M.CS_ROOM_ENTER(player, data)
    local roomId = data.roomId
    if player.room then
        return {
            code = RoomConst.ENTER_RESULT_CODE.ALREADY_IN_ROOM
        }
    end

    local code, room = RoomService:enterRoom(player.id, roomId)
    if not room then
        return {
            code = code
        }
    end

    room = Service:new(room)
    local enterCode = room:enter(player.id)
    local result = {
        code = enterCode
    }

    if enterCode == RoomConst.ENTER_RESULT_CODE.SUCCESS then
        player.room = room
    end

    return result
end

return M
